package com.finger.forest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.data.TileCache;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.utils.DownloadUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 展示本地离线地图
 */
public class OfflineMapDetailActivity extends AppCompatActivity {

  private static final String TAG = OfflineMapDetailActivity.class.getSimpleName();

  private MapView mMapView;

  String filePath = null;
  String fileName = "offline_map.mp3";
  String downUrl = "http://192.168.1.240:9999/group1/M00/00/03/wKgB8F5oyQmAYV3BAABW-XUr6DA839.mp3";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_offline_map_detail);

    filePath = getExternalFilesDir(null).getAbsolutePath();

    // get a reference to the map view
    mMapView = findViewById(R.id.mapView);
    ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
    mMapView.setAttributionTextVisible(false);

    ImageView ivRight = findViewById(R.id.ivRight);
    ivRight.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(OfflineMapDetailActivity.this, OfflineMapDataActivity.class);
        startActivity(intent);
      }
    });

    ImageView btn_back = findViewById(R.id.btn_back);
    btn_back.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
      }
    });

    String filePathName = filePath +"/"+ fileName;
    Log.i(TAG, "离线文件路径："+ filePathName);

    //将assets文件复制
    try {
      String fileName = getExternalFilesDir(null).getAbsolutePath()+"/offline_map.tpk";
      File file = new File(fileName);
      if (!file.exists()) {
        InputStream is = getAssets().open("offline_map.tpk");
        inputstreamtofile(is, file);
      }
      //已经取得了file对象

    } catch (IOException e) {
      e.printStackTrace();
    }

    //判断离线地图文件是否存在，不存在则下载
    File offLineFile = new File(filePathName);
    /*if (!offLineFile.exists()){
      //不存在，去下载
      downFile(fileName,downUrl);
    } else {*/
      //存在，则加载
      setMap();
    //}

  }

  public void inputstreamtofile(InputStream ins, File file)
          throws IOException {
    OutputStream os = new FileOutputStream(file);
    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
      os.write(buffer, 0, bytesRead);
    }
    os.close();
    ins.close();
  }

  private void setMap(){
    Log.i(TAG,"加载地图");
    // create a basemap from a local tile package
    String filePath = getExternalFilesDir(null).getAbsolutePath()+"/offline_map.tpk";
    Log.i(TAG,"离线文件路径："+filePath);
    TileCache tileCache = new TileCache(filePath);
    ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tileCache);
    Basemap basemap = new Basemap(tiledLayer);

    ArcGISMap map = new ArcGISMap(basemap);
    // set the map to be displayed in the Map View
    mMapView.setMap(map);
  }

  @Override
  protected void onPause() {
    mMapView.pause();
    super.onPause();
  }

  @Override
  protected void onResume() {
    super.onResume();
    mMapView.resume();
  }

  @Override
  protected void onDestroy() {
    mMapView.dispose();
    super.onDestroy();
  }

  /**
   * 下载文件
   * @param name
   * @param urlString
   */
  public void downFile(String name, String urlString) {
    DownloadUtil.get().download(urlString, filePath, name, new DownloadUtil.OnDownloadListener() {
      @Override
      public void onDownloadSuccess(File file) {
        //下载完成后，再加载地图
        setMap();
        Log.v(TAG, "下载成功");
        Looper.prepare();//增加部分
        Looper.loop();//增加部分
      }

      @Override
      public void onDownloading(int progress) {
        Log.v(TAG, "下载进度" + progress);
        //progressDialog.setProgress(progress);
      }

      @Override
      public void onDownloadFailed(Exception e) {
//        if (progressDialog != null && progressDialog.isShowing()) {
//            progressDialog.dismiss();
//        }

      }
    });
  }

}

